package www.dianbaozu.com.wxapi

import android.os.Bundle
import androidx.activity.viewModels
import com.netease.nim.uikit.xpopup.CreateXPopupHelper
import com.netease.nim.uikit.xpopup.PopupViewEntity
import com.orhanobut.logger.Logger
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.modelbase.BaseReq
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler
import dagger.hilt.android.AndroidEntryPoint
import www.dianbaozu.com.R
import www.wen.com.common.databinding.ActivityWxEntryBinding
import www.wen.com.common.lib.base.activity.BaseLoadingActivity
import www.wen.com.common.lib.base.module.BaseViewModel
import www.wen.com.common.lib.data.entities.LastWxLogin
import www.wen.com.common.lib.data.entities.NavigationEntity
import www.wen.com.common.lib.data.entities.Result
import www.wen.com.common.lib.extension.getString
import www.wen.com.common.lib.extension.postObject
import www.wen.com.common.lib.extension.toast
import www.wen.com.common.lib.helper.loading.KeyHelper
import www.wen.com.common.lib.util.WxUtil

/**
 * @author WEN
 * @Description:
 * @date 2020/12/29 23:41
 */
@AndroidEntryPoint
class WXEntryActivity :
    BaseLoadingActivity<ActivityWxEntryBinding>(),
    IWXAPIEventHandler {

    private var api: IWXAPI? = null

    private val wxEntryViewModel: WXEntryViewModel by viewModels()

    override val viewModel: BaseViewModel
        get() = wxEntryViewModel

    override fun getLayout(): Int = R.layout.activity_wx_entry

    override fun initialize() {
        api = WxUtil.getIWXAPI(this)
        api!!.handleIntent(intent, this);
    }

    // 微信发送请求到第三方应用时，会回调到该方法
    override fun onReq(req: BaseReq) {
        Logger.i("WXEntryActivity -> onReq() ->  req.type = " + req.type)
    }

    // 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
    override fun onResp(resp: BaseResp) {
        when (resp.type) {
            ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX ->
                when (resp.errCode) {
                    BaseResp.ErrCode.ERR_OK -> {
                        finish()
                        Logger.i("WXEntryActivity -> onResp() ->  req.type = COMMAND_SENDMESSAGE_TO_WX, resp.errCode = BaseResp.ErrCode.ERR_OK")
                    }
                    BaseResp.ErrCode.ERR_USER_CANCEL -> {
                        finish()
                        Logger.i("WXEntryActivity -> onResp() ->  req.type = COMMAND_SENDMESSAGE_TO_WX, resp.errCode = BaseResp.ErrCode.ERR_USER_CANCEL")
                    }
                    BaseResp.ErrCode.ERR_AUTH_DENIED -> {
                        finish()
                        Logger.i("WXEntryActivity -> onResp() ->  req.type = COMMAND_SENDMESSAGE_TO_WX, resp.errCode = BaseResp.ErrCode.ERR_AUTH_DENIED")
                    }
                    BaseResp.ErrCode.ERR_UNSUPPORT -> {
                        finish()
                        Logger.i("WXEntryActivity -> onResp() ->  req.type = COMMAND_SENDMESSAGE_TO_WX, resp.errCode = BaseResp.ErrCode.ERR_UNSUPPORT")
                    }
                    else -> {
                        finish()
                        Logger.i("WXEntryActivity -> onResp() ->  req.type = COMMAND_SENDMESSAGE_TO_WX, resp.errCode = BaseResp.ErrCode.ELSE(code = ${resp.errCode})")
                    }
                }

            ConstantsAPI.COMMAND_SENDAUTH ->
                when (resp.errCode) {
                    BaseResp.ErrCode.ERR_OK -> {
                        wxEntryViewModel.wxLogin((resp as SendAuth.Resp).code, {
                            if(it == null)  {
                                finish()
                                return@wxLogin
                            }
                            if (it.user.forbidStatus) {
                                CreateXPopupHelper.createInformPopupView(PopupViewEntity().apply {
                                    isShow = true
                                    context = this@WXEntryActivity
                                    title = getString(R.string.the_count_is_ban)
                                    content = "因以下原因,用户「${it.user.nickName}」 已被封禁：\n\n【${it.user.forbidReason}】\n\n在 ${it.user.unForbidTime}之前，该账号不能进行登录"
                                    confirmContent = getString(R.string.got_it)
                                    confirmFunction = { basePopupView->
                                        basePopupView.dismiss()
                                        finish()
                                    }
                                })
                            }else{
                                toast("登录失败")
                                finish()
                            }
                        }) {
                            if(it is Result<*>){
                                postObject(KeyHelper.LOGIN_FRAGMENT_KEY, true)
                            }else if(it is LastWxLogin){
                                postObject(KeyHelper.LOGIN_FRAGMENT_KEY,
                                        NavigationEntity(
                                                R.id.action_loginFragment_to_bindPhoneFragment,
                                                bundle = Bundle().apply {
                                                    putString(KeyHelper.MMKV_ACCESS_TOKEN, it.accessToken)
                                                    putString(KeyHelper.MMKV_OPEN_ID, it.openId)
                                                }
                                        ))
                            }
                            finish()
                        }
                        Logger.i("WXEntryActivity -> onResp() ->  req.type = COMMAND_SENDAUTH, resp.errCode = BaseResp.ErrCode.ERR_OK")
                    }
                    BaseResp.ErrCode.ERR_USER_CANCEL -> {
                        finish()
                        Logger.i("WXEntryActivity -> onResp() ->  req.type = COMMAND_SENDAUTH, resp.errCode = BaseResp.ErrCode.ERR_USER_CANCEL")
                    }
                    BaseResp.ErrCode.ERR_AUTH_DENIED -> {
                        finish()
                        Logger.i("WXEntryActivity -> onResp() ->  req.type = COMMAND_SENDAUTH, resp.errCode = BaseResp.ErrCode.ERR_AUTH_DENIED")
                    }
                    BaseResp.ErrCode.ERR_UNSUPPORT -> {
                        finish()
                        Logger.i("WXEntryActivity -> onResp() ->  req.type = COMMAND_SENDAUTH, resp.errCode = BaseResp.ErrCode.ERR_UNSUPPORT")
                    }
                    else -> {
                        finish()
                        Logger.i("WXEntryActivity -> onResp() ->  req.type = COMMAND_SENDAUTH, resp.errCode = BaseResp.ErrCode.ELSE(code = ${resp.errCode})")
                    }
                }
        }
    }


}